<template>
  <el-container style="height: 950px; border: 1px solid #eee">
    <el-aside width="350px">
      <el-container>
        <!--   患者选择区      -->
        <el-header style="padding: 0;margin: 0">
          <el-row>
            <el-col :span="21" style="text-align: left">
              <el-tag>患者选择：</el-tag>
            </el-col>
            <el-col :span="3" style="text-align: right">
              <el-button type="primary" size="small" @click="reloadUser" style="margin-right: 5px">
                <el-icon>
                  <Refresh/>
                </el-icon>
              </el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-input placeholder="请输入内容" v-model="inputPatient" style="width: 100%">
              <template #prepend>
                患者名：
              </template>
              <template #append>
                <el-icon>
                  <Search/>
                </el-icon>
              </template>
            </el-input>

          </el-row>
        </el-header>
        <el-main style="height: 800px;padding: 0;margin: 0">
          <el-tabs type="border-card" @tab-click="findPatient">
            <el-tab-pane label="本人" name="self">
              <el-tag size="small">未诊患者：</el-tag>
              <el-table ref="singleTable" :data="RegistersTable01" highlight-current-row
                        @row-click="handleCurrentChange01"
                        @row-dblclick="handleDBCurrentChange"
                        style="width: 100%;height: 50%" :show-header="false" max-height="400" size="small">
                <el-table-column property="casenumber" label="病历号" width="80">
                </el-table-column>
                <el-table-column property="realname" label="姓名">
                </el-table-column>
                <el-table-column property="age" label="年龄" width="50">
                </el-table-column>
              </el-table>
              <br/><br/>
              <el-tag size="small">已诊患者：</el-tag>
              <el-table ref="singleTable" :data="RegistersTable02" @row-click="handleCurrentChange02"
                        @row-dblclick="handleDBCurrentChange"
                        style="width: 100%;height: 50%" :show-header="false" size="small">
                <el-table-column property="casenumber" label="病历号" width="80">
                </el-table-column>
                <el-table-column property="realname" label="姓名">
                </el-table-column>
                <el-table-column property="age" label="年龄" width="50">
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="科室*" name="dept">
              <el-tag>未诊患者：</el-tag>

              <el-table ref="singleTable" :data="MyPatientsData01" highlight-current-row
                        style="width: 100%;height: 50%" :show-header="false" size="small">
                <el-table-column property="casenumber" label="病历号" width="80">
                </el-table-column>
                <el-table-column property="realname" label="姓名">
                </el-table-column>
                <el-table-column property="age" label="年龄" width="50">
                </el-table-column>
              </el-table>
              <el-tag>已诊患者：</el-tag>
              <el-table ref="singleTable" :data="MyPatientsData02"
                        style="width: 100%;height: 50%" :show-header="false" size="small">
                <el-table-column property="casenumber" label="病历号" width="80">
                </el-table-column>
                <el-table-column property="realname" label="姓名">
                </el-table-column>
                <el-table-column property="age" label="年龄" width="50">
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-main>
      </el-container>
    </el-aside>

    <el-container direction="vertical" style="height: 950px">
      <el-row>

        <span style="margin-left: 20px;font-size: small;" :span="20">{{ showPatientsTop }}</span>
        <el-button type="text" size="small" style="float: right;margin-right: 20px;" @click="endRegister"
                   v-if="showStop" :span="2">诊毕
        </el-button>

      </el-row>

      <!--
        门诊主要功能区
      -->
      <el-tabs type="border-card" :before-leave="toTab">
        <!-- 患者检查填写  -->
        <el-tab-pane label="病历首页">
          <!-- 1. 门诊病历 -->
          <el-container v-loading="loading">


            <!-- 页面正文 -->
            <el-main style="width:100%;background:#fff;height:800px;overflow-y: auto">
              <el-form ref="form" :model="medicalRecord01" label-width="80px" label-position="left" size="small">
                <el-row style="background-color: #EAF1F5;margin-top: -20px">
                  <el-col :span="8" style="margin-top: 4px;">

                  </el-col>
                  <el-col :span="4">
                    <el-button type="text" size="small" @click="stageCheck">暂存</el-button>
                  </el-col>
                  <el-col :span="4">
                    <el-button type="text" size="small" @click="saveCheck">提交</el-button>
                  </el-col>
                  <el-col :span="4">
                    <el-button type="text" size="small" :disabled="isSaved" @click="cleanCheck">清空所有</el-button>
                  </el-col>
                  <el-col :span="4">
                    <el-button type="text" size="small" @click="refMedicalRecord">刷新</el-button>
                  </el-col>
                </el-row>
                <el-tag>病史内容：</el-tag>
                <el-form-item label="主诉">
                  <el-input type="textarea" :rows="1" :autosize="{ minRows: 2, maxRows: 10 }"
                            v-model="medicalRecord01.readme" :disabled="isSaved"></el-input>
                </el-form-item>
                <el-form-item label="现病史">
                  <el-input type="textarea" :rows="2" :autosize="{ minRows: 2, maxRows: 10 }"
                            v-model="medicalRecord01.present" :disabled="isSaved"></el-input>
                </el-form-item>
                <el-form-item label="现病治疗情况">
                  <el-input type="textarea" :rows="2" :autosize="{ minRows: 2, maxRows: 10 }"
                            v-model="medicalRecord01.presenttreat" :disabled="isSaved"></el-input>
                </el-form-item>
                <el-form-item label="既往史">
                  <el-input type="textarea" :rows="2" :autosize="{ minRows: 2, maxRows: 10 }"
                            v-model="medicalRecord01.history" :disabled="isSaved"></el-input>
                </el-form-item>
                <el-form-item label="过敏史">
                  <el-input type="textarea" :rows="2" :autosize="{ minRows: 2, maxRows: 10 }"
                            v-model="medicalRecord01.allergy" :disabled="isSaved"></el-input>
                </el-form-item>
                <el-form-item label="体格检查">
                  <el-input type="textarea" :rows="2" :autosize="{ minRows: 2, maxRows: 10 }"
                            v-model="medicalRecord01.physique" :disabled="isSaved"></el-input>
                </el-form-item>
                <el-form-item label="诊断">
                  <el-input type="textarea" :rows="2" :autosize="{ minRows: 2, maxRows: 10 }"
                            v-model="medicalRecord01.diagnosis" :disabled="isSaved"></el-input>
                </el-form-item>

                <el-form-item label="检查建议">
                  <el-input type="textarea" :rows="2" :autosize="{ minRows: 2, maxRows: 10 }"
                            v-model="medicalRecord01.proposal" :disabled="isSaved"></el-input>
                </el-form-item>
                <el-form-item label="注意事项">
                  <el-input type="textarea" :rows="2" :autosize="{ minRows: 2, maxRows: 10 }"
                            v-model="medicalRecord01.careful" :disabled="isSaved"></el-input>
                </el-form-item>
              </el-form>
              <el-button type="text" size="small" @click="saveCheck">提交</el-button>
            </el-main>

          </el-container>
        </el-tab-pane>
        <!-- 医生给患者根据病历要求患者进行的检查项：一般无比对标准，如B超 -->
        <el-tab-pane label="检查申请" :lazy="true" @click="checkCase1">
          <div>
            <el-container direction="horizontal" >
              <!-- 页面弹窗 -->
              <el-dialog
                  title="新增检查申请" v-model="dialog01Visible" width="30%" v-if="currentPatient.casenumber"
              >
                <el-form size="small">
                  <el-form-item>
                    <el-input placeholder="请输入内容" style="width: 100%">
                      <template #prepend>检查名称：</template>
                      <template #append><el-button icon="Search"></el-button></template>
                    </el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-table border :data="tableData01" size="small" max-height="300px">
                      <el-table-column prop="choose01" label="" width="30px">
                        <template #default="scope" >
                          <input type="radio" name="chooseOne01" :value="scope.row.id"/>
                        </template>
                      </el-table-column>
                      <el-table-column label="申请名称" width="80">
                        <template #default="scope">
                          {{ scope.row.itemname?.substring(0, 3) || '' }}
                        </template>
                      </el-table-column>
                      <el-table-column property="itemname" label="项目" >
                      </el-table-column>
                    </el-table>
                  </el-form-item>
                  <el-form-item label="检查科室">
                    <el-select placeholder="请选择">
                      <el-option
                          v-for="item in tableData01.value"
                          :key="item.keshi"
                          :label="item.keshi"
                          :value="item.keshi">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="是否加急：">
                    <el-switch
                        v-model="switch01"
                        active-color="#13ce66">
                    </el-switch>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="dialog01Visible = false">确 定</el-button>
                    <el-button @click="dialog01Visible = false">取 消</el-button>
                  </el-form-item>
                </el-form>
              </el-dialog>


              <!-- 页面正文 -->
              <el-aside style="width: 700px;height: 500px;">

                <el-row style="background-color: #EAF1F5">
                  <el-col :span="10" style="margin-top: 1px;">
                    <el-tag size="small">本项目金额合计：</el-tag>
                    <el-tag type="warning" size="small">235.00元</el-tag>
                  </el-col>
                  <el-col :span="3">
                    <el-button type="text" size="small" @click="dialog01Visible=true">新增项目</el-button>
                  </el-col>
                  <el-col :span="3">
                    <el-button type="text" size="small" @click="deleteConfirm('删除选择的检查项目')">删除项目</el-button>
                  </el-col>
                  <el-col :span="2">
                    <el-button type="text" size="small" @click="saveConfirm">开立</el-button>
                  </el-col>

                </el-row>

                <el-form ref="form" label-width="80px">
                  <el-row>
                    <el-col :span="2" style="margin-top: 40px;">
                      <el-input type="textarea" :rows="4" :disabled="true" style="width: 45px;" v-model="msg01">

                      </el-input>
                    </el-col>
                    <el-col :span="22" style="margin-top: 4px;">
                      <el-table ref="singleTable" :data="tableData01"
                                style="width: 100%;margin: 0px;padding: 0px;" :show-header="true">
                        <el-table-column type="selection">
                        </el-table-column>
                        <el-table-column label="申请名称" width="80">
                          <template #default="scope">
                            {{ scope.row.itemname.substring(0, 3)}}
                          </template>
                        </el-table-column>
                        <el-table-column property="itemname" label="项目">
                        </el-table-column>
                        <el-table-column property="deptname" label="执行科室" width="80">
                        </el-table-column>
                        <el-table-column property="isurgent" label="加急" width="80">
                        </el-table-column>
                        <el-table-column property="state" label="状态" width="80">
                        </el-table-column>
                        <el-table-column property="danjia" label="单价" width="80">
                        </el-table-column>
                        <el-table-column property="jieguo" label="检验结果" width="80">
                          <template slot-scope="scope">
                            <el-popover
                                placement="right"
                                width="400"
                                trigger="click">
                              <img src=""></img>
                              <el-button slot="reference" type="text" size="small">查看</el-button>
                            </el-popover>

                          </template>
                        </el-table-column>

                      </el-table>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-form-item label="目的要求">
                      <el-input type="textarea" :rows="4" placeholder="【检验目的：】【患者主诉：】【现病史：】"></el-input>
                    </el-form-item>
                  </el-row>

                </el-form>
              </el-aside>
              <el-main style="margin-top: -20px;">
                <el-tabs type="card" v-model="activeName">


                </el-tabs>
              </el-main>
            </el-container>

          </div>
        </el-tab-pane>
        <!-- 医生给患者根据病历要求患者进行的检验项：一般有比对标准，如血常规 -->
        <el-tab-pane label="检验申请*" :lazy="true" @click="checkCase2">
          <div>
            <!-- 3.检验申请 -->
            <el-container direction="horizontal">
              <!-- 页面弹窗 -->
              <el-dialog title="新增检验申请" v-model="dialog02Visible" width="30%" v-if="currentPatient.casenumber">
                <el-form size="small">
                  <el-form-item>
                    <el-input placeholder="请输入内容" style="width: 100%">
                      <template #prepend>检验名称：</template>
                      <template #append><el-button icon="Search"></el-button></template>
                    </el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-table border :data="tableData02" size="small" max-height="300px">
                      <el-table-column prop="choose02" label="" width="30px">
                        <template #default="scope">
                          <input type="radio" name="chooseOne02" @click="table2id=scope.$index"/>
                        </template>
                      </el-table-column>
                      <el-table-column label="申请名称" width="80">
                        <template #default="scope">
                          {{ scope.row.itemname?.substring(0, 3) || '' }}
                        </template>
                      </el-table-column>
                      <el-table-column property="itemname" label="项目">
                      </el-table-column>
                    </el-table>
                  </el-form-item>
                  <el-form-item label="检验科室">
                    <el-select placeholder="请选择" v-if="tableData02.length>0" v-model="tableData02[0].deptname">
                      <el-option
                          :key="tableData02[0].deptname"
                          :label="tableData02[0].deptname"
                          :value="tableData02[0].deptname"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="是否加急：">
                    <el-switch
                        v-model="tableData2.isurgent"
                        active-color="#13ce66">
                    </el-switch>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="saveTest">确 定</el-button>
                    <el-button @click="dialog02Visible = false">取 消</el-button>
                  </el-form-item>
                </el-form>
              </el-dialog>


              <!-- 页面正文 -->
              <el-aside style="width: 700px;height: 500px;">

                <el-row style="background-color: #EAF1F5">
                  <el-col :span="10" style="margin-top: 1px;">
                    <el-tag size="small">本项目金额合计：</el-tag>
                    <el-tag type="warning" size="small">0.00元</el-tag>
                  </el-col>
                  <el-col :span="3">
                    <el-button type="text" size="small" @click="dialog02Visible=true">
                      新增项目
                    </el-button>
                  </el-col>
                  <el-col :span="3">
                    <el-button type="text" size="small" @click="showConfirm('删除选择的检验项目')">删除项目</el-button>
                  </el-col>
                  <el-col :span="2">
                    <el-button type="text" size="small" @click="showConfirm('使科室收到开立的检验项目')">开立</el-button>
                  </el-col>

                </el-row>

                <el-form ref="form" label-width="80px">
                  <el-row>
                    <el-col :span="2" style="margin-top: 40px;">
                      <el-input type="textarea" :rows="4" :disabled="true" style="width: 45px;" v-model="msg01">

                      </el-input>
                    </el-col>
                    <el-col :span="22" style="margin-top: 4px;">
                      <el-table ref="singleTable" :data="tableData2"
                                style="width: 100%;margin: 0px;padding: 0px;" :show-header="true">
                        <el-table-column type="selection">
                        </el-table-column>
                        <el-table-column label="申请名称" width="80">
                          <template #default="scope">
                            {{ scope.row.Name.substring(0, 3)}}
                          </template>
                        </el-table-column>
                        <el-table-column property="Name" label="项目">
                        </el-table-column>
                        <el-table-column property="deptname" label="执行科室" width="80">
                        </el-table-column>
                        <el-table-column label="加急" width="80">
                          <template #default="scope">
                            {{ scope.row.IsUrgent === 0 ? '否' : '是' }}
                          </template>
                        </el-table-column>
                        <el-table-column label="状态" width="80">
                          <template #default="scope">
                            {{ scope.row.State === 0 ? '暂存' : '已开立' }}
                          </template>
                        </el-table-column>
                        <el-table-column property="price" label="单价" width="80">
                        </el-table-column>
                        <el-table-column prop="result" label="检验结果" width="80">
                          <template #default="scope">
                            <el-popover
                                placement="right"
                                :width="400"
                                trigger="click">
                              <img src="../picture/img.png"/>
                              <template #reference>
                                <el-button type="text" size="small">查看详细</el-button>
                              </template>
                            </el-popover>
                          </template>
                        </el-table-column>

                      </el-table>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-form-item label="目的要求">
                      <el-input type="textarea" :rows="4" placeholder="【检验目的：】【患者主诉：】【现病史：】" v-model="tableData2.objective"></el-input>
                    </el-form-item>
                  </el-row>

                </el-form>
              </el-aside>
              <el-main style="margin-top: -20px;">
                <el-tabs type="card" v-model="activeName">


                </el-tabs>
              </el-main>
            </el-container>

          </div>
        </el-tab-pane>
        <!-- 患者病历填写  -->
        <el-tab-pane label="门诊确诊*" :lazy="true">

        </el-tab-pane>


      </el-tabs>
    </el-container>
  </el-container>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {dayjs, ElMessage, ElNotification} from 'element-plus'
import service from '@/utils/request'
import {Search} from "@element-plus/icons-vue";
import {useCounterStore} from "@/stores/counter.js";

const counter = useCounterStore();
let switch01=ref(false);
let switch02=ref(false);
let table2id=-1,charge=0;

let dialog01Visible = ref(false)
let dialog02Visible = ref(false)

let tableData01=ref([])
let tableData02=ref([])
let tableData=ref({})
let tableData2=ref([])
let selectedTestItem=ref([])
let RegistersTable01 = ref([])
let RegistersTable02 = ref([])
let MyPatientsData01 = ref([])
let MyPatientsData02 = ref([])

let medicalRecord = ref({MedicalDisease01: [], MedicalDisease02: []})
let medicalRecord01 = ref({})
let showPatientsTop = ref("请选择患者")
let inputPatient = ref("")
let currentPatient=ref({})

function checkCase1() {
  if(!currentPatient.value.casenumber){
    ElMessage.warning("请选择已经提交病历的患者")
    dialog01Visible.value=false;
  }else{
    service.get("/fmeditem/getbyrecordtype?id=1").then(
        res => {
          console.log(res.data)
          tableData01.value=res.data;
          console.log(tableData01.value);
        }
    )
  }
}
function checkCase2() {
  if(!currentPatient.value.casenumber){
    ElMessage.warning("请选择已经提交病历的患者")
    dialog01Visible.value=false;
  }else{
    service.get("/fmeditem/getbyrecordtype?id=2").then(
        res => {
          tableData02.value=res.data;
        }
    )
  }
}
function saveTest() {
  tableData.value.medicalid=currentPatient.value.casenumber;
  tableData.value.registid=currentPatient.value.registid;
  tableData.value.itemid=tableData02.value[table2id].id;
  tableData.value.name=tableData02.value[table2id].itemname;
  tableData.value.creationtime=new Date().toISOString();
  tableData.value.doctorid=counter.vo_user.value.id;
  tableData.value.checkoperid=2;
  tableData.value.resultoperid=2;
  tableData.value.num=1;
  tableData.value.state=0;
  tableData.value.recordtype=2;
  service.post("/check/add", tableData.value).then(
      res => {
        ElMessage.success('提交成功');
      })
      .catch(error => {
        ElMessage.error('提交失败: ' + (error.response?.data?.message || error.message));
      });
  dialog02Visible.value=false;
  if(currentPatient.value&&currentPatient.value.registid){
    service.get("/check/getbyregistid?id="+currentPatient.value.registid).then(
        res=>{
          tableData2.value=res.data;
          console.log(tableData2.value)
        }
    )
  }
}
function saveConfirm(){

}
function handleDBCurrentChange(row) {   //双击选中患者
  showPatientsTop.value = "患者姓名:" + row.realname + " .  病历号:" + row.casenumber + " .  年龄:" + row.age + " .  性别:" + (row.gender===71?'男':'女');
  inputPatient.value = row.realname;
  dialog01Visible.value=false;
  dialog02Visible.value=false;
  service.get("/medicalrecord/getbycasenumber?id=" + row.casenumber).then(
      res => {
        if (res.data[0]) {
          medicalRecord01.value = res.data[0];
        } else {
          medicalRecord01.value={};
          medicalRecord01.value.casenumber = row.casenumber;
          medicalRecord01.value.registid = row.registerid;
        }
        currentPatient.value=medicalRecord01.value;
        if(currentPatient.value&&currentPatient.value.registid){
          service.get("/check/getbyregistid?id="+currentPatient.value.registid).then(
              res=>{
                tableData2.value=res.data;
                console.log(tableData2.value)
              }
          )
        }
      }
  )
}

function findPatient(tab) {
  if (tab.props.name == "self") {
    service.get("/register/getbyuserid?id=" + counter.vo_user.value.id).then(
        res => {
          RegistersTable01.value = res.data.unprocessedPatients;
          RegistersTable02.value = res.data.processedPatients;
        }
    )
  } else if (tab.props.name == "dept") {
    service.get("/register/getbydeptid?id=" + counter.vo_user.value.deptID).then(
        res => {
          MyPatientsData01.value = res.data.unprocessedPatients;
          MyPatientsData02.value = res.data.processedPatients;
        }
    )
  }
}

function stageCheck() {
  // 设置默认值
  medicalRecord01.value.casestate = '1';
  console.log(medicalRecord01.value)
  service.post("/medicalrecord/add", medicalRecord01.value).then(
      res => {
        ElMessage.success('暂存成功');
        // clear(); // 清空表单
      })
      .catch(error => {
        ElMessage.error('暂存失败: ' + (error.response?.data?.message || error.message));
      });
}

function saveCheck() {
  // 验证必填字段
  if (!medicalRecord01.value.readme || !medicalRecord01.value.present ||
      !medicalRecord01.value.presenttreat||!medicalRecord01.value.history||
      !medicalRecord01.value.allergy||!medicalRecord01.value.physique||
      !medicalRecord01.value.proposal||!medicalRecord01.value.careful) {
    ElMessage.error('请填写所有必填字段');
    return;
  }

  // 设置默认值
  medicalRecord01.value.casestate = '2';
  service.post("/medicalrecord/add", medicalRecord01.value).then(
      res => {
        ElMessage.success('提交成功');
        // clear(); // 清空表单
      })
      .catch(error => {
        ElMessage.error('提交失败: ' + (error.response?.data?.message || error.message));
      });
}

function cleanCheck(){
  medicalRecord01.value={};
}

function refMedicalRecord() {
  if(currentPatient.casenumber){
    service.get("/medicalrecord/getbycasenumber?id=" + currentPatient.casenumber).then(
        res => {
          if (res.data[0]) {
            medicalRecord01.value = res.data[0];
          } else {
            medicalRecord01.value={};
            medicalRecord01.value.casenumber = row.casenumber;
            medicalRecord01.value.registid = row.registerid;
          }
          console.log(medicalRecord01.value.readme);
        }
    )
  }
}


onMounted(() => {
  // 加载本人 已诊患者、未诊患者，本科室已诊患者，未诊患者
  // console.log(dialog02Visible)
  // console.log(counter.vo_user.value.id)
})
</script>